<?php

namespace App\Http\Middleware;

use Closure;
use \Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;

class ValidateApiSign
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next){
        $xml_str = file_get_contents('php://input');
        $obj_message = simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);
        $arr_message = json_decode(json_encode($obj_message), true);
        return redirect('/');
        if (!is_array($arr_message)){
            return redirect('/');
        }
        $sign =  $arr_message['sign'];
        unset($arr_message['sign']);
        ksort($arr_message );
        $str_wanyuanKey = config('apiConfig.sign_key');
        $temp = http_build_query($obj_message)."&key=$str_wanyuanKey";
        $str_mySign = strtoupper(md5($temp)) ;
        if ($str_mySign!= $sign){
            Log::info('XML FORBIDDEN{{ XML：',$xml_str.' mySign:'.$str_mySign.'}}');
            return redirect('/');
        }
        $request->attributes->add(['arr_xmlData'=>$arr_message]);
        return $next($request);
    }
}
